package com.begamer.card.controller;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.begamer.card.cache.Cache;
import com.begamer.card.cache.PlayerInfo;
import com.begamer.card.common.dao.hibernate.CommDao;
import com.begamer.card.common.util.Random;
import com.begamer.card.common.util.RequestUtil;
import com.begamer.card.common.util.Statics;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.binRead.RankData;
import com.begamer.card.common.util.binRead.VipData;
import com.begamer.card.json.command2.PkBattleJson;
import com.begamer.card.json.command2.PkBattleLogJson;
import com.begamer.card.json.command2.PkBattleLogResultJson;
import com.begamer.card.json.command2.PkBattleResultJson;
import com.begamer.card.json.command2.PkRankJson;
import com.begamer.card.json.command2.PkRankResultJson;
import com.begamer.card.json.command2.PkRecordJson;
import com.begamer.card.json.command2.PkRecordResultJson;
import com.begamer.card.json.command2.RankJson;
import com.begamer.card.json.command2.RankResultJson;
import com.begamer.card.json.element.PkRankElement;
import com.begamer.card.json.element.PkRecordElement;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.log.PlayerLogger;
import com.begamer.card.model.pojo.Announce;
import com.begamer.card.model.pojo.Card;
import com.begamer.card.model.pojo.CardGroup;
import com.begamer.card.model.pojo.Mail;
import com.begamer.card.model.pojo.PkRank;
import com.begamer.card.model.pojo.Player;
import com.begamer.card.model.pojo.SpeciaMail;

public class PkController extends AbstractMultiActionController {
	private static final Logger logger = Logger.getLogger(PkController.class);
	private static Logger playlogger = PlayerLogger.logger;
	private static Logger errorlogger = ErrorLogger.logger;
	@Autowired
	private CommDao commDao;

	/** 进入pk系统* */
	public ModelAndView entryPk(HttpServletRequest request,
			HttpServletResponse response)
	{
		try
		{
			// 检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			// 获取参数
			RankJson rj = JSONObject.toJavaObject(jsonObject, RankJson.class);
			RankResultJson rrj = new RankResultJson();
			if (rj != null)
			{
				PlayerInfo pi = Cache.getInstance().getPlayerInfo(rj.playerId,
						request.getSession());
				if (pi != null)
				{
					// 校验模块是否解锁
					if (UiController.checkMode(9, pi))
					{
						long curTime = System.currentTimeMillis();
						int s = (int) (curTime - pi.pkcdtime) / 1000;
						if (rj.type == 0)// 排位赛
						{
							PkRank pr = Cache.getInstance().getRankById(
									pi.player.getId());
							if (pr != null)
							{
								int rank = pr.getRank();
								int rankAward = 0;
								RankData rData = RankData.getRankdata(pi.player
										.getLevel());
								if (pr.getRank() == 0)// 第一次进竞技场
								{
									rankAward = 0;
									rank = Cache.getInstance().getMaxRank() + 1;
									pr.setRank(rank);
								}
								else
								{// 排名奖励
									rankAward = rankAward(pi.player.getLevel(),
											pr);
								}
								String str1 = "";
								int pkNum = rData.number1
										+ pi.player.getBuyPkNumTimes()
										- pr.getPkNum();
								str1 = pr.getRank() + "-"
										+ pr.getRankAwardType() + "-"
										+ pr.getPvpAward() + "-" + pkNum + "-"
										+ rankAward;
								rrj.s = str1;
								List<String> ss = getPkRanks(rank);
								List<String> cardIds =new ArrayList<String>();
								for(int i=0;i<ss.size();i++)
								{
									if(ss.get(i)!=null)
									{
										String [] temp =ss.get(i).split("-");
										PlayerInfo pInfo =Cache.getInstance().getPlayerInfo(StringUtil.getInt(temp[0]));
										String card =null;
										Card [] cards =pInfo.getCardGroup().getCards();
										for(int m=0;m<cards.length;m++)
										{
											if(cards[m]!=null)
											{
												if(card !=null && card.length()>0)
												{
													card =card+"-"+cards[m].getCardId();
												}
												else
												{
													card =cards[m].getCardId()+"";
												}
											}
										}
										cardIds.add(card);
									}
									else
									{
										errorlogger.error("pk对象出错!!!");
									}
								}
								rrj.ss = ss;
								rrj.cardIds =cardIds;
								rrj.sAward = rData.award * rData.number;
								rrj.sPknum = rData.number1;
								if (pi.pkcdtime != 0)
								{
									if (s >= 5 * 60)
									{
										rrj.cdtime = 0;
									}
									else
									{
										rrj.cdtime = 5 * 60 - s;
									}
								}
							}
							else
							{
								logger.error("pr不存在");
							}
							playlogger.info("|区服："
									+ Cache.getInstance().serverId + "|玩家："
									+ pi.player.getId() + "|"
									+ pi.player.getName() + "|等级："
									+ pi.player.getLevel() + "|进入排位赛");
						}
						else if (rj.type == 1)// 天位赛
						{
							playlogger.info("|区服："
									+ Cache.getInstance().serverId + "|玩家："
									+ pi.player.getId() + "|"
									+ pi.player.getName() + "|等级："
									+ pi.player.getLevel() + "|进入天位赛");
						}
						else if (rj.type == 2)// 夺宝奇兵
						{
							playlogger.info("|区服："
									+ Cache.getInstance().serverId + "|玩家："
									+ pi.player.getId() + "|"
									+ pi.player.getName() + "|等级："
									+ pi.player.getLevel() + "|进入夺宝奇兵");
						}
						if (pi.player.getNewPlayerType() == 21)// 新手竞技场
						{
							pi.player.setNewPlayerType(pi.player
									.getNewPlayerType() + 1);
						}
					}
					else
					{
						rrj.errorCode = 56;
					}
				}
				else
				{
					rrj.errorCode = -3;
				}
			}
			else
			{
				rrj.errorCode = -1;
			}
			Cache.recordRequestNum(rrj);
			String msg = JSON.toJSONString(rrj);
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}

	public ModelAndView pkBattleInit(HttpServletRequest request,
			HttpServletResponse response)
	{
		try
		{
			// 检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			// 获取参数
			PkBattleJson pbj = JSONObject.toJavaObject(jsonObject,
					PkBattleJson.class);
			PkBattleResultJson pbrj = new PkBattleResultJson();
			if (pbj != null)
			{
				PlayerInfo pi = Cache.getInstance().getPlayerInfo(pbj.playerId,
						request.getSession());
				PlayerInfo pi1 = Cache.getInstance().getPlayerInfo(pbj.pkId);
				int errorcode = 0;
				if (pi != null && pi1 != null)
				{
					// 校验
					PkRank pr = Cache.getInstance().getRankById(
							pi.player.getId());
					CardGroup cg0 = pi.getCardGroup();
					CardGroup cg1 = pi1.getCardGroup();
					long curTime = System.currentTimeMillis();
					int sTime = (int) (curTime - pi.pkcdtime) / 1000;
					if (errorcode == 0)
					{
						if (pi.pkcdtime != 0)
						{
							if (sTime < 5 * 60)
							{
								errorcode = 86;
							}
						}
					}
					if (pr.getPkNum() >= 10 + pi.player.getBuyPkNumTimes())// 校验挑战次数
					{
						errorcode = 50;
					}
					// 校验卡组
					if (errorcode == 0)
					{
						if (cg0 == null || cg1 == null)
						{
							errorcode = 73;
						}
					}
					if (errorcode == 0)// 校验卡组是否有卡
					{
						if ((!cg0.canFight()) || (!cg1.canFight()))
						{
							errorcode = 65;
						}
					}
					// 功能
					if (errorcode == 0)
					{
						pbrj.cs0 = cg0.getBattleData();
						pbrj.cs1 = cg1.getBattleData();
						// 双方合体技
						int[] us0 = new int[3];
						us0[0] = cg0.unitId;
						int[] us1 = new int[3];
						us1[0] = cg1.unitId;

						pbrj.us0 = us0;
						pbrj.us1 = us1;
						pbrj.bNum = pi.bNum + 1;
						pbrj.pkId = pbj.pkId;
						int[] maxEnergys = { pi.player.getMaxEnergy(),
								pi1.player.getMaxEnergy() };
						int[] initEnergys = {
								VipData.getInitEnergy(pi.player.getVipLevel()),
								VipData.getInitEnergy(pi1.player.getVipLevel()) };
						pbrj.mes = maxEnergys;
						pbrj.initEs = initEnergys;
						int[] battlePowers = { pi.player.getBattlePower(),
								pi1.player.getBattlePower() };
						pbrj.bps = battlePowers;
						String[] names = { pi.player.getName(),
								pi1.player.getName() };
						pbrj.ns = names;
						int[] levels = { pi.player.getLevel(),
								pi1.player.getLevel() };
						pbrj.lvs = levels;

						String[] runes = { pi.player.getRune(),
								pi1.player.getRune() };
						pbrj.runes = runes;
						pr.setPkNum(pr.getPkNum() + 1);
						// 开始冷却时间
						pi.pkcdtime = System.currentTimeMillis();
						RankData rData = RankData.getRankdata(pi.player
								.getLevel());
						int sumAward = rData.number * rData.award;
						if (pr.getPvpAward() < sumAward)
						{
							pi.player.addRuneNum(rData.award);
							pr.setPvpAward(pr.getPvpAward() + rData.award);
						}
						// 记录每日任务进度
						ActivityController.updateTaskComplete(3, pi, 1);
						pi.player.addActive(3,1);
						/** GM 功能* */
						List<SpeciaMail> speciaMails = commDao
								.getSpeciaMails(1);
						if (speciaMails != null && speciaMails.size() > 0)
						{
							long curTime1 = System.currentTimeMillis();
							boolean is = false;
							for (SpeciaMail speciaMail1 : speciaMails)
							{
								is = speciaMail1.isTrue(curTime1);
								if (is && pr.pkNum == speciaMail1.getValue())// 完成n场竞技场发邮件
								{
									Mail mail = Mail.createMail(pr.playerId,
											"GM", speciaMail1.getTitle(),
											speciaMail1.getContent(),
											speciaMail1.getReward1(),
											speciaMail1.getReward2(),
											speciaMail1.getReward3(),
											speciaMail1.getReward4(),
											speciaMail1.getReward5(),
											speciaMail1.getReward6(),
											speciaMail1.getGold(), speciaMail1
													.getCrystal(), speciaMail1
													.getRuneNum(), speciaMail1
													.getPower(), speciaMail1
													.getFriendNum(),
											speciaMail1.getDeleteTime());
									Cache.getInstance().sendMail(mail);
									logger.info("发送完成" + pr.pkNum + "场jjc邮件");
								}
							}

						}
						else
						{
							logger.info("没有邮件要发送");
						}
						/** GM功能结束* */
						// 掉落
						int num = Random.getNumber(0, 1000);
						List<String> s = new ArrayList<String>();
						int st = 0;
						int end = 0;
						for (int i = 0; i < rData.drops.size(); i++)
						{
							if (rData.drops.get(i) != null
									&& rData.drops.get(i).length() > 0)
							{
								String[] temp = rData.drops.get(i).split("-");
								end = StringUtil.getInt(temp[2]) + st;
								if (num > st && num <= end)
								{
									String[] str = temp[1].split(",");
									String ss = temp[0] + "-" + str[0] + "-"
											+ str[1];
									s.add(ss);
									break;
								}
								st = end;
							}
						}
						pbrj.ds = s;
						pbrj.raceAtts1 = Statics.getRaceAttris(pi);
						pbrj.raceAtts2 = Statics.getRaceAttris(pi1);
						// 记录战斗信息
						pi.pbrj = pbrj;

						// 自己和目标的排名
						PkRank pkRank1 = Cache.getInstance().getRankById(
								pi.player.getId());
						PkRank pkRank2 = Cache.getInstance().getRankById(
								pi1.player.getId());
						int rank1 = 0;
						int rank2 = 0;
						if (pkRank1 != null && pkRank2 != null)
						{
							rank1 = pkRank1.rank;
							rank2 = pkRank2.rank;
						}
						playlogger.info("|区服：" + Cache.getInstance().serverId
								+ "|玩家：" + pi.player.getId() + "|"
								+ pi.player.getName() + "|等级："
								+ pi.player.getLevel() + "|pk开始:"
								+ pi1.player.getId() + "|自己排名:" + rank1
								+ ",目标排名:" + rank2);
					}
					else
					{
						pbrj.errorCode = errorcode;
					}
				}
				else
				{
					pbrj.errorCode = -3;
				}
			}
			else
			{
				pbrj.errorCode = -1;
			}
			Cache.recordRequestNum(pbrj);
			String msg = JSON.toJSONString(pbrj);
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}

	public ModelAndView pkBattleOver(HttpServletRequest request,
			HttpServletResponse response)
	{
		try
		{
			// 检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			// 获取参数
			PkBattleLogJson plj = JSONObject.toJavaObject(jsonObject,
					PkBattleLogJson.class);
			PkBattleLogResultJson plrj = new PkBattleLogResultJson();
			if (plj != null)
			{
				PlayerInfo pi = Cache.getInstance().getPlayerInfo(plj.playerId,
						request.getSession());
				if (pi != null)
				{
					// 校验
					int errorcode = 0;
					Player p = Cache.getInstance().getPlayer(pi.pbrj.pkId);// pk对象
					PkRank pr0 = Cache.getInstance().getRankById(
							pi.player.getId());// 自己pr
					PkRank pr1 = Cache.getInstance().getRankById(pi.pbrj.pkId);// pk对象pr
					boolean rr = true;
					if (pr0.getRank() < pr1.rank)// 自己>pk对象 名次变化为0
					{
						rr = false;
					}
					// 功能
					if (errorcode == 0)
					{
						plrj.rank0 =pr0.getRank();
						int bNum = plj.bNum;
						if (pi.bNum < bNum && pi.pbrj.bNum == bNum)// 第一次请求
						{
							RankData rData = RankData.getRankdata(pi.player
									.getLevel());
							int type0 = 0;
							int type1 = 1;
							if (plj.r == 1)// win
							{
								pr0.setWinNum(pr0.getWinNum() + 1);// 修改玩家胜利次数
								plrj.power0 = pi.player.getPower();
								if (pr0.getRank() > pr1.getRank())// 与pk玩家交换排名
								{
									int rank0 = pr0.getRank();
									pr0.setRank(pr1.getRank());
									plrj.rank = pr0.getRank();
									pr1.setRank(rank0);
								}
								plrj.power1 = pi.player.getPower();
								// 更新成就
								pi.player.updateAchieve(12, pr0.getRank() + "");
							}
							if(plj.r == 1){
								plrj.honor = rData.honorwin;
								pi.player.addPvpHonor(rData.honorwin);
							}else{
								plrj.honor = rData.honorlose;
								pi.player.addPvpHonor(rData.honorlose);
							}
							plrj.name = p.getName();// pk对象
							plrj.runeNum = pr0.getPvpAward();
							plrj.award = rData.award;
							plrj.sAward =rData.award*rData.number;
							// 将掉落物品放进背包
							List<String> drops = pi.pbrj.ds;
							List<Integer> cardIds =new ArrayList<Integer>();
							for (int i = 0; i < drops.size(); i++)
							{
								if (drops.get(i) != null
										&& drops.get(i).length() > 0)
								{
									String[] temp = drops.get(i).split("-");
									switch (StringUtil.getInt(temp[0])) {
									case 1:// item
										pi.addItem(StringUtil.getInt(temp[1]),
												StringUtil.getInt(temp[2]));
										break;
									case 2:// equip
										int e = StringUtil.getInt(temp[2]);
										for (int j = 0; j < e; j++)
										{
											pi.addEquip(StringUtil
													.getInt(temp[1]));
										}
										break;
									case 3:// card
										int c = StringUtil.getInt(temp[2]);
										cardIds.add(StringUtil.getInt(temp[1]));
										for (int j = 0; j < c; j++)
										{
											pi.addCard(StringUtil
													.getInt(temp[1]), 1);
										}
										break;
									case 4:// skill
										int s = StringUtil.getInt(temp[2]);
										for (int j = 0; j < s; j++)
										{
											pi.addSkill(StringUtil
													.getInt(temp[1]), 1);
										}
										break;
									case 5:// passiveskill
										int ps = StringUtil.getInt(temp[2]);
										for (int j = 0; j < ps; j++)
										{
											pi.addPassiveSkill(StringUtil
													.getInt(temp[1]));
										}
										break;
									}
								}
							}
							if(cardIds.size()>0)
							{
								pi.getNewUnitSkill(cardIds);
							}
							plrj.r = plj.r;
							pi.bNum = pi.bNum + 1;
							pi.pblrj = plrj;

							/** GM 功能* */
							List<SpeciaMail> speciaMails = commDao
									.getSpeciaMails(2);
							if (speciaMails != null && speciaMails.size() > 0)
							{
								long curTime = System.currentTimeMillis();
								boolean is = false;
								for (SpeciaMail speciaMail2 : speciaMails)
								{
									is = speciaMail2.isTrue(curTime);
									if (is
											&& pr0.winNum == speciaMail2
													.getValue())// 获得n场竞技场胜利发邮件
									{
										Mail mail = Mail.createMail(
												pr0.playerId, "GM", speciaMail2
														.getTitle(),
												speciaMail2.getContent(),
												speciaMail2.getReward1(),
												speciaMail2.getReward2(),
												speciaMail2.getReward3(),
												speciaMail2.getReward4(),
												speciaMail2.getReward5(),
												speciaMail2.getReward6(),
												speciaMail2.getGold(),
												speciaMail2.getCrystal(),
												speciaMail2.getRuneNum(),
												speciaMail2.getPower(),
												speciaMail2.getFriendNum(),
												speciaMail2.getDeleteTime());
										Cache.getInstance().sendMail(mail);
										logger.info("发送胜利" + pr0.winNum
												+ "场jjc邮件");
									}
								}
							}
							else
							{
								logger.info("没有邮件要发送");
							}
							/** GM功能结束* */

							/** 记录对战信息* */
							String pkrecord0 = pr0.getPkrecord();// 自己
							String pkrecord1 = pr1.getPkrecord();// 目标
							int rank0 = 0;
							int rank1 = 0;
							int r0 = plj.r;
							int r1 = 1;// 目标胜利
							if (plj.r == 1)
							{
								r1 = 2;// 目标失败
							}
							if (plj.r == 1)
							{
								if (pr0.rank < pr1.rank)// 自己>pk的对象
								{
									if (rr)// 自己<pk对象
									{
										rank0 = pr0.getRank();
										rank1 = pr1.getRank();
									}

								}
							}
							// type(0,挑战别人,1,别人来挑战)-id(pk玩家的id)-rank(0,排名不变,x提升或者下降至x名)-r(1胜利，0失败)-time(记录时间)
							String record0 = type0
									+ "&"
									+ pr1.getPlayerId()
									+ "&"
									+ rank0
									+ "&"
									+ r0
									+ "&"
									+ StringUtil.getDateTime(System
											.currentTimeMillis());
							String record1 = type1
									+ "&"
									+ pr0.getPlayerId()
									+ "&"
									+ rank1
									+ "&"
									+ r1
									+ "&"
									+ StringUtil.getDateTime(System
											.currentTimeMillis());
							if (pkrecord0 != null && pkrecord0.length() > 0)
							{
								String[] temp = pkrecord0.split(",");
								if (temp.length >= 10)// 记录已经超过十条
								{
									String s = "";
									for (int i = 1; i < temp.length; i++)
									{
										if (s == null || s.length() == 0)
										{
											s = temp[i];
										}
										else
										{
											s = s + "," + temp[i];
										}
									}
									pkrecord0 = s + "," + record0;
								}
								else
								{
									pkrecord0 = pkrecord0 + "," + record0;
								}

							}
							else
							{
								pkrecord0 = record0;
							}
							if (pkrecord1 != null && pkrecord1.length() > 0)
							{
								String[] temp = pkrecord1.split(",");
								if (temp.length >= 10)// 记录已经超过十条
								{
									String s = "";
									for (int i = 1; i < temp.length; i++)
									{
										if (s == null || s.length() == 0)
										{
											s = temp[i];
										}
										else
										{
											s = s + "," + temp[i];
										}
									}
									pkrecord1 = s + "," + record1;
								}
								else
								{
									pkrecord1 = pkrecord1 + "," + record1;
								}
							}
							else
							{
								pkrecord1 = record1;
							}
							pr0.setPkrecord(pkrecord0);
							pr1.setPkrecord(pkrecord1);
						}
						else
						{
							plrj = pi.pblrj;
						}
						// 自己和目标的排名
						PkRank pkRank1 = Cache.getInstance().getRankById(
								pi.player.getId());
						int rank1 = 0;
						if (pkRank1 != null)
						{
							rank1 = pkRank1.rank;
						}
						playlogger.info("|区服：" + Cache.getInstance().serverId
								+ "|玩家：" + pi.player.getId() + "|"
								+ pi.player.getName() + "|等级："
								+ pi.player.getLevel() + "|pk结束,排名" + rank1);
						// --pk结束如果第一名则发公告--//
						if (rank1 == 1)
						{
							Announce e = Announce.createAnnounce(0,"玩家"
									+ pi.player.getName()
									+ "在竞技场战斗中英勇无比，获得了第一名！", 1, 1, 1);
							Cache.instance.addAnnounce(e);
						}
//						//pvp排名n~n奖励
//						GmSpecialMailUtil.getInstance().pvpRankingSpeciaMail(pi.player.getId(), pi.player.getName(), pi.player.getLevel(), rank1);
					}
					else
					{
						plrj.errorCode = errorcode;
					}

				}
				else
				{
					plrj.errorCode = -3;
				}
			}
			else
			{
				plrj.errorCode = -1;
			}

			Cache.recordRequestNum(plrj);
			String msg = JSON.toJSONString(plrj);
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}


	/**刷新对手玩家 新机制**/
	public static List<String> getPkRanks(int rank)
	{
		List<String> list =new ArrayList<String>();
		int num =rank;
		HashMap<Integer, Integer> pkMap2 =new HashMap<Integer, Integer>();
		if(rank>30)//30以后的名次，先按照新的机制随机出来十个对手玩家，然后从十个对手玩家中随机出来四个作为最终对手玩家
		{
			List<Integer> ss =new ArrayList<Integer>();
			HashMap<Integer, Integer> pkMap =new HashMap<Integer, Integer>();
			int num1 =num-(int)(num*0.25);//随机出七个
			int m1=0;
			for(int i=0;i<7+m1;i++)
			{
				int rand =Random.getNumber(num1, num);
				if(!pkMap.containsKey(rand))
				{
					pkMap.put(rand, rand);
					ss.add(rand);
				}
				else
				{
					m1++;
				}
			}
			int num2 =num-(int)(num*0.35);//随机出两个
			int m2=0;
			for(int i=0;i<2+m2;i++)
			{
				int rand =Random.getNumber(num2, num1);
				if(!pkMap.containsKey(rand))
				{
					pkMap.put(rand, rand);
					ss.add(rand);
				}
				else
				{
					m2++;
				}
			}
			int num3 =num-(int)(num*0.5);//随机出一个
			int m3=0;
			for(int i=0;i<1+m3;i++)
			{
				int rand =Random.getNumber(num3, num2);
				if(!pkMap.containsKey(rand))
				{
					pkMap.put(rand, rand);
					ss.add(rand);
				}
				else
				{
					m3++;
				}
			}
			//至此，pkmap中已经有十个不同的名次
			//从十个不同名次中随机出来四个不同的名次
			int m4=0;
			for(int i=0;i<4+m4;i++)
			{
				int rand =Random.getNumber(0, 10);
				if(!pkMap2.containsKey(ss.get(rand)))
				{
					pkMap2.put(ss.get(rand), ss.get(rand));
				}
				else
				{
					m4++;
				}
			}
			for(int i:pkMap2.values())
			{
				PkRank pr = Cache.getInstance().getPkRankByRank(i);
				Player p = Cache.getInstance().getPlayer(pr.getPlayerId());
				if (pr != null)
				{
					if (p != null)
					{
						String s = p.getId() + "-" + p.getName() + "-"
								+ p.getHead() + "-" + pr.getRank() + "-"
								+ p.getBattlePower();
						list.add(s);
					}
					else
					{
						errorlogger.info("获取不到玩家!");
					}
				}
				else
				{
					errorlogger.info("该名次玩家不存在!");
					continue;
				}
			}
		}
		else if(rank>=6 && rank<=30)//6-30名次的玩家，直接取玩家名次的前四个名次作为对手玩家
		{
			for(int i=1;i<5;i++)
			{
				PkRank pr = Cache.getInstance().getPkRankByRank(rank-i);
				Player p = Cache.getInstance().getPlayer(pr.getPlayerId());
				if (pr != null)
				{
					if (p != null)
					{
						String s = p.getId() + "-" + p.getName() + "-"
								+ p.getHead() + "-" + pr.getRank() + "-"
								+ p.getBattlePower();
						list.add(s);
					}
					else
					{
						errorlogger.info("获取不到玩家!");
					}
				}
				else
				{
					errorlogger.info("该名次玩家不存在!");
					continue;
				}
			}
		}
		else if(rank<6)//前五名玩家，对手玩家为除了自己之外的其他四个名次玩家
		{
			for (int i = 6; i > 1; i--)
			{
				if (i - 1 != rank)
				{
					PkRank pr = Cache.getInstance().getPkRankByRank(i - 1);
					Player p = Cache.getInstance().getPlayer(pr.getPlayerId());
					if (pr != null)
					{
						if (p != null)
						{
							String s = p.getId() + "-" + p.getName() + "-"
									+ p.getHead() + "-" + pr.getRank() + "-"
									+ p.getBattlePower();
							list.add(s);
						}
						else
						{
							errorlogger.info("获取不到玩家!");
						}
					}
					else
					{
						errorlogger.info("该名次玩家不存在!");
						continue;
					}
				}
			}
		}
		//排序。rank从大到小
		for(int i=0;i<list.size();i++)
		{
			for(int j=0;j<list.size()-1;j++)
			{
				String [] str =list.get(j).split("-");
				String [] str1 =list.get(j+1).split("-");
				if(StringUtil.getInt(str[3])<StringUtil.getInt(str1[3]))
				{
					String s =list.get(j);
					list.set(j, list.get(j+1));
					list.set(j+1,s);
				}
			}
		}
		return list;
	}
	
	/** 排行榜查询* */
	public ModelAndView rankList(HttpServletRequest request,
			HttpServletResponse response)
	{
		try
		{
			// 检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			// 获取参数
			PkRankJson prj = JSONObject.toJavaObject(jsonObject,
					PkRankJson.class);
			PkRankResultJson prrj = new PkRankResultJson();
			if (prj != null)
			{
				PlayerInfo pi = Cache.getInstance().getPlayerInfo(prj.playerId,
						request.getSession());
				if (pi != null)
				{
					HashMap<Integer, PkRank> pkMap = Cache.getInstance()
							.getPkRankMap2();// key is rank ,value is pr
					int size = 0;
					if (pkMap != null && pkMap.size() > 0)
					{

						if (pkMap.size() < 20 && pkMap.size() > 0)
						{
							size = pkMap.size();
						}
						else if (pkMap.size() >= 20)
						{
							size = 20;
						}
					}
					List<PkRankElement> pes = new ArrayList<PkRankElement>();
					if (size > 0)
					{
						for (int i = 0; i < size; i++)
						{
							PkRank pr = pkMap.get(i + 1);
							if (pr != null)
							{
								Player p = Cache.getInstance().getPlayer(
										pr.getPlayerId());
								int award = 0;
								int honor = 0;
								if (pr.getPlayerLevel() != p.getLevel())
								{
									pr.setPlayerLevel(p.getLevel());
								}
								award = rankAward(pi.player.getLevel(), pr);
								honor = rankAward1(pi.player.getLevel(), pr);
								// award =rankAward(pr.getPlayerLevel(), pr);
								PkRankElement pre = new PkRankElement();
								pre.setData(p, pr.rank, award,honor);
								pes.add(pre);
							}
						}
					}
					prrj.pes = pes;
					playlogger.info("|区服：" + Cache.getInstance().serverId
							+ "|玩家：" + pi.player.getId() + "|"
							+ pi.player.getName() + "|等级："
							+ pi.player.getLevel() + "|pk排行榜查询");
				}
				else
				{
					prrj.errorCode = -3;
				}
			}
			else
			{
				prrj.errorCode = -1;
			}

			Cache.recordRequestNum(prrj);
			String msg = JSON.toJSONString(prrj);
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}

	/** 获取排名奖励* */
	public static Integer rankAward(int lv, PkRank pr)
	{
		RankData rData = RankData.getRankdata(lv);
		List<String> ranks = new ArrayList<String>();
		ranks = rData.rank;
		int st = 0;
		int end = 0;
		int rankAward = 0;
		int playerRank = pr.getRank();
		for (int j = 0; j < ranks.size(); j++)
		{
			if (ranks.get(j) != null && ranks.get(j).length() > 0)
			{
				String[] temp = ranks.get(j).split("-");
				end = StringUtil.getInt(temp[0]);
				if (playerRank > st && playerRank <= end)
				{
					rankAward = StringUtil.getInt(temp[1]);
					break;
				}
				else
				{
					st = end;
				}
			}
			else
			{
				errorlogger.info("排名奖励为空");
			}
		}
		return rankAward;
	}
	
	/** 获取排名奖励* */
	public static Integer rankAward1(int lv, PkRank pr)
	{
		RankData rData = RankData.getRankdata(lv);
		List<String> ranks = new ArrayList<String>();
		ranks = rData.rank;
		int st = 0;
		int end = 0;
		int rankAward = 0;
		int playerRank = pr.getRank();
		for (int j = 0; j < ranks.size(); j++)
		{
			if (ranks.get(j) != null && ranks.get(j).length() > 0)
			{
				String[] temp = ranks.get(j).split("-");
				end = StringUtil.getInt(temp[0]);
				if (playerRank > st && playerRank <= end)
				{
					rankAward = StringUtil.getInt(temp[2]);
					break;
				}
				else
				{
					st = end;
				}
			}
			else
			{
				errorlogger.info("排名奖励为空");
			}
		}
		return rankAward;
	}

	/** 对战记录* */
	public ModelAndView pkRecord(HttpServletRequest request,
			HttpServletResponse response)
	{
		try
		{
			// 检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			// 获取参数
			PkRecordJson pj = JSONObject.toJavaObject(jsonObject,
					PkRecordJson.class);
			PkRecordResultJson prj = new PkRecordResultJson();
			if (pj != null)
			{
				PlayerInfo pi = Cache.getInstance().getPlayerInfo(pj.playerId,
						request.getSession());
				if (pi != null)
				{
					List<PkRecordElement> list = new ArrayList<PkRecordElement>();
					PkRank pr = Cache.getInstance().getRankById(
							pi.player.getId());
					if (pr != null)
					{
						String pkrecord = pr.getPkrecord();// type(0,挑战别人,1,别人来挑战)&id(pk玩家的id)&rank(0,排名不变,x提升或者下降至x名)&r(1胜利，0失败)&time(记录时间)
						if (pkrecord != null && pkrecord.length() > 0)
						{
							String[] record = pkrecord.split(",");
							for (int i = record.length - 1; i >= 0; i--)
							{
								if (record[i] != null && record[i].length() > 0)
								{
									String[] temp = record[i].split("&");
									long time = StringUtil
											.getTimeStamp(temp[4]);
									if (System.currentTimeMillis() - time >= 2 * 24 * 3600 * 1000)
									{
										break;
									}
									else
									{
										list
												.add(new PkRecordElement(
														record[i]));
									}
								}
							}
						}
					}
					prj.list = list;
					playlogger.info("|区服：" + Cache.getInstance().serverId
							+ "|玩家：" + pi.player.getId() + "|"
							+ pi.player.getName() + "|等级："
							+ pi.player.getLevel() + "|pk对战记录");
				}
				else
				{
					prj.errorCode = -3;
				}
			}
			else
			{
				prj.errorCode = -1;
			}

			Cache.recordRequestNum(prj);
			String msg = JSON.toJSONString(prj);
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
}
